'use client'

import NavIcons from '@/components/im-system/NavIcons'
import Sidebar from '@/components/im-system/Sidebar'
import UserAvatar from '@/components/im-system/UserAvatar'
import { DragContext } from '@/contexts/DragContext'
import { useWebSocket } from '@/hooks/useWebSocket'
import { usePathname, useRouter } from 'next/navigation'
import { useEffect, useRef, useState } from 'react'

export default function ImSystemLayout({ children }: { children: React.ReactNode }) {
	const router = useRouter()
	const pathname = usePathname()
	// 窗口状态
	const [position, setPosition] = useState({ x: 0, y: 0 })
	const [size, setSize] = useState({ width: 1200, height: 800 })
	const containerRef = useRef<HTMLDivElement>(null)

	// 拖拽状态
	const [isDragging, setIsDragging] = useState(false)
	const [dragStart, setDragStart] = useState({ x: 0, y: 0 })

	// 缩放状态
	const [isResizing, setIsResizing] = useState(false)
	const [resizeDirection, setResizeDirection] = useState<string | null>(null)
	const [resizeStart, setResizeStart] = useState({ x: 0, y: 0 })

	// 导航状态
	const [activeTab, setActiveTab] = useState<RouterType>('chat')

	// 初始化窗口位置到屏幕中央
	useEffect(() => {
		if (containerRef.current) {
			const rect = containerRef.current.getBoundingClientRect()
			setPosition({
				x: (window.innerWidth - rect.width) / 2,
				y: (window.innerHeight - rect.height) / 2,
			})
		}
	}, [])

	// 处理拖拽
	const handleMouseDown = (e: React.MouseEvent) => {
		setIsDragging(true)
		setDragStart({
			x: e.clientX - position.x,
			y: e.clientY - position.y,
		})
	}

	// 处理开始调整大小
	const handleResizeStart = (e: React.MouseEvent, direction: string) => {
		e.stopPropagation()
		setIsResizing(true)
		setResizeDirection(direction)
		setResizeStart({
			x: e.clientX,
			y: e.clientY,
		})
	}

	// 处理调整大小
	const handleResize = (e: MouseEvent) => {
		if (!isResizing || !resizeDirection) return

		const deltaX = e.clientX - resizeStart.x
		const deltaY = e.clientY - resizeStart.y

		const minWidth = 800
		const minHeight = 600
		const maxWidth = window.innerWidth - position.x
		const maxHeight = window.innerHeight - position.y

		let newWidth = size.width
		let newHeight = size.height
		let newX = position.x
		let newY = position.y

		switch (resizeDirection) {
			case 'se':
				newWidth = Math.min(Math.max(size.width + deltaX, minWidth), maxWidth)
				newHeight = Math.min(Math.max(size.height + deltaY, minHeight), maxHeight)
				break
			case 'sw':
				newWidth = Math.min(Math.max(size.width - deltaX, minWidth), window.innerWidth - newX)
				newHeight = Math.min(Math.max(size.height + deltaY, minHeight), maxHeight)
				newX = Math.max(0, position.x + size.width - newWidth)
				break
			case 'ne':
				newWidth = Math.min(Math.max(size.width + deltaX, minWidth), maxWidth)
				newHeight = Math.min(Math.max(size.height - deltaY, minHeight), window.innerHeight - newY)
				newY = Math.min(
					Math.max(0, position.y + size.height - newHeight),
					position.y + size.height - minHeight
				)
				break
			case 'nw':
				newWidth = Math.min(Math.max(size.width - deltaX, minWidth), window.innerWidth - newX)
				newHeight = Math.min(Math.max(size.height - deltaY, minHeight), window.innerHeight - newY)
				newX = Math.max(0, position.x + size.width - newWidth)
				newY = Math.min(
					Math.max(0, position.y + size.height - newHeight),
					position.y + size.height - minHeight
				)
				break
		}

		setSize({ width: newWidth, height: newHeight })
		setPosition({ x: newX, y: newY })
		setResizeStart({ x: e.clientX, y: e.clientY })
	}

	// 全局鼠标事件处理
	useEffect(() => {
		const handleGlobalMouseMove = (e: MouseEvent) => {
			if (isDragging) {
				const newX = e.clientX - dragStart.x
				const newY = e.clientY - dragStart.y
				const maxX = window.innerWidth - (containerRef.current?.offsetWidth || 0)
				const maxY = window.innerHeight - (containerRef.current?.offsetHeight || 0)

				setPosition({
					x: Math.min(Math.max(0, newX), maxX),
					y: Math.min(Math.max(0, newY), maxY),
				})
			} else if (isResizing) {
				handleResize(e)
			}
		}

		const handleGlobalMouseUp = () => {
			setIsDragging(false)
			setIsResizing(false)
			setResizeDirection(null)
		}

		document.addEventListener('mousemove', handleGlobalMouseMove)
		document.addEventListener('mouseup', handleGlobalMouseUp)

		return () => {
			document.removeEventListener('mousemove', handleGlobalMouseMove)
			document.removeEventListener('mouseup', handleGlobalMouseUp)
		}
	}, [isDragging, dragStart, isResizing, resizeDirection])

	// 处理标签切换
	const handleTabChange = (tab: RouterType) => {
		setActiveTab(tab)
		router.push(`/im-system/${tab}`)
	}

	// 根据当前路径设置激活的标签
	useEffect(() => {
		const currentTab = pathname.split('/').pop() as RouterType
		if (currentTab && currentTab !== 'im-system') {
			setActiveTab(currentTab)
		}
	}, [pathname])

	useWebSocket()

	const dragContextValue = {
		handleMouseDown,
	}

	return (
		<div className="min-h-screen bg-gray-100">
			<div
				ref={containerRef}
				className="fixed"
				style={{
					left: position.x,
					top: position.y,
					width: size.width,
					height: size.height,
					cursor: isDragging ? 'grabbing' : 'default',
				}}
			>
				{/* 调整大小的手柄 */}
				<div
					className="absolute top-0 left-0 w-4 h-4 cursor-nw-resize"
					onMouseDown={(e) => handleResizeStart(e, 'nw')}
				/>
				<div
					className="absolute top-0 right-0 w-4 h-4 cursor-ne-resize"
					onMouseDown={(e) => handleResizeStart(e, 'ne')}
				/>
				<div
					className="absolute bottom-0 left-0 w-4 h-4 cursor-sw-resize"
					onMouseDown={(e) => handleResizeStart(e, 'sw')}
				/>
				<div
					className="absolute bottom-0 right-0 w-4 h-4 cursor-se-resize"
					onMouseDown={(e) => handleResizeStart(e, 'se')}
				/>

				<DragContext.Provider value={dragContextValue}>
					<div className="w-full h-full flex rounded-lg shadow-lg overflow-hidden">
						<Sidebar>
							<UserAvatar />
							<NavIcons activeTab={activeTab} onTabChange={handleTabChange} />
						</Sidebar>

						<main className="flex-1 bg-white">{children}</main>
					</div>
				</DragContext.Provider>
			</div>
		</div>
	)
}
